package org.testfire.translator.watij;

import org.testfire.model.FinderType;
import org.testfire.model.HtmlFinderType;
import org.testfire.model.TestsetType;
import org.testfire.translator.TestFireTranslator;
import org.testfire.translator.TranslatorFactory;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Sep 2, 2007
 * Time: 3:52:34 PM
 *
 */
public class HtmlFinderToWatijTranslator<T> implements TestFireTranslator<HtmlFinderType>
{

    /**
     * Translate an HtmlFinder XML object to valid Java code.
     *  
     * @return The source code.
     */
    public Object translate( TestsetType testset, HtmlFinderType hf )
    {
        StringBuilder buf = new StringBuilder();

        String key = hf.getKey();
        if ( key != null && key.length() > 0 )
        {
            testset.registerVariableKey( key, hf.getKeyType() );
            buf.append( key ).append( " = " );
        }

        if ( hf.getUseObjectKey() != null && hf.getUseObjectKey().length() > 0 )
        {
            buf.append( hf.getUseObjectKey() );
            buf.append( "." );
        }
        else if ( hf.getFinder() != null )
        {

            if ( hf.getName().equals( "frame" ) && hf.getFinder().getName().equals( "index" ) )
            {
                /* Index is broken for frames. This is a hack. */
                /* @todo Deprecate index, find a way to deal with frames. */
                buf.append( "frames().get( " );
                FinderType finder = hf.getFinder();
                for ( String fkey : hf.getFinder().getParams().keySet() )
                {
                    buf.append( finder.getParams().get( fkey ).toArgumentString() ).append( ", " );
                }
                if ( finder.getParams().size() > 0 )
                {
                    buf.delete( buf.length() - 2, buf.length() );
                }
                buf.append( ")" );
            }
            else
            {
                buf.append(
                    String.format( "%1$s(%2$s).", hf.getName(), TranslatorFactory.get( FinderType.class ).translate(
                        testset, hf.getFinder() ) ) );
            }
        }

        // buf = 'something.'
        if ( hf.getHtmlFinderType() != null && hf.getCommand() == null )
        { // currently MUST have a hf.getFinder() if we have an htmlFinderType...
            buf.append( this.translate( testset, hf.getHtmlFinderType() ) );
        }
        if ( hf.getCommand() != null )
        {
            /*
            *  So 'hf.getCommand()' would be the last on a potentially very long chain of htmlFindersTypes.
            *  But only the hf.getCommand() knows if there is a return type or not.
            */
            buf = new StringBuilder( String.format( TranslatorFactory.get( hf.getCommand().getClass() ).translate(
                testset, hf.getCommand() ).toString(), buf, hf.getKey() ) );
        }
        return buf.toString();
    }
}